package com.example.myapplication.View;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.Interface.HttpCallbackListener;
import com.example.myapplication.R;
import com.example.myapplication.Util.HttpUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HttpConnectActivity extends AppCompatActivity {

    private TextView responseText;
    private TextView text;
    private static final int UPDATE_TEXT = 1;
    private Handler handler = new Handler(){
        public void handleMessage(Message msg){
            text.setText("nice to meet you");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.http_connect_activity);

        Button button1 = (Button)findViewById(R.id.send_request);
        responseText = (TextView)findViewById(R.id.response_text);
        button1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                sendRequestWithHttpURLConnection();
            }
        });
        Button button2 = (Button)findViewById(R.id.ok_http);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendRequestWithOkHttp();
            }
        });
        Button button3 = (Button)findViewById(R.id.send_http_callback);
        button3.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                String address = "https://www.baidu.com";
                HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
                    @Override
                    public void onFinish(String response) {
                        showResponse(response);
                    }

                    @Override
                    public void onError(Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        });

        Button button4 = (Button)findViewById(R.id.ok_http_callback);
        button4.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                HttpUtil.sendOKHttprequest("https://www.baidu.com", new okhttp3.Callback(){
                    @Override
                    public void onResponse(Call call, Response response)throws IOException{
                        String responseData = response.body().toString();
                        showResponse(responseData);
                    }

                    @Override
                    public void onFailure(Call call, IOException e){
                        e.printStackTrace();
                    }
                });
            }
        });

        Button button5 = (Button)findViewById(R.id.change_text);
        text = (TextView)findViewById(R.id.text);
        button5.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                new Thread(new Runnable(){
                    @Override
                    public void run(){
                        Message message = new Message();
                        message.what = UPDATE_TEXT;
                        handler.sendMessage(message);
                    }
                }).start();
            }
        });
    }

    private void sendRequestWithOkHttp(){
        Thread thread = new Thread(new Runnable(){
            @Override
            public void run(){
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("https://www.baidu.com")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().toString();
                    Log.d("okhttpresponsebody", response.toString());
                    showResponse(responseData);
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }

    private void sendRequestWithHttpURLConnection(){
        Thread thread = new Thread(new Runnable(){
            @Override
            public void run(){
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("https://www.baidu.com");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();

                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while((line = reader.readLine()) != null){
                        response.append(line);
                    }
                    showResponse(response.toString());
                }catch(Exception e){
                    e.printStackTrace();
                }finally{
                    if (reader != null){
                        try {
                            reader.close();
                        }catch(IOException e){
                            e.printStackTrace();
                        }
                    }
                    if (connection != null){
                        connection.disconnect();
                    }
                }
            }
        });
        thread.start();
    }

    private void showResponse(final String response){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseText.setText(response);
            }
        });
    }

}
